package com.hydroid.vds.vds;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.nio.ByteBuffer;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE = 83;
    MediaProjectionManager mMediaProjectionManager;
    private int mScreenWidth;
    private int mScreenHeight;
    private ImageReader mImageReader;
    private int mScreenDensity;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private Handler handler1;
    private Runnable r;

    int Num = 0;
    private Runnable r1;
    private String TAG = "mainActivity";

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        mScreenWidth = metrics.widthPixels;
        mScreenHeight = metrics.heightPixels;
        mScreenDensity = metrics.densityDpi;

//        mScreenWidth = getWindow().getDecorView().getRootView().getWidth();
//        mScreenHeight = getWindow().getDecorView().getRootView().getHeight();

        createImageReader();
        mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);


        handler1 = new Handler();

        r1 = new Runnable() {
            @Override
            public void run() {
                TextView tx = (TextView) findViewById(R.id.text);
                tx.setText("wait capture " + Num++);

                Image image = mImageReader.acquireLatestImage();
                if (image == null) {
                    handler1.postDelayed(r1, 50);
                    return;
                }

                tx.setText("hello Capture Num " + Num++);

                int width = image.getWidth();
                int height = image.getHeight();
                final Image.Plane[] planes = image.getPlanes();
                final ByteBuffer buffer = planes[0].getBuffer();
                //每个像素的间距
                int pixelStride = planes[0].getPixelStride();
                //总的间距
                int rowStride = planes[0].getRowStride();
                int rowPadding = rowStride - pixelStride * width;
                Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
                bitmap.copyPixelsFromBuffer(buffer);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
//                        Bitmap bitmap = takeScreenshot(getWindow().getDecorView(), mScreenWidth, mScreenHeight);
                Drawable a = new BitmapDrawable(bitmap);
                tx.setCompoundDrawablesWithIntrinsicBounds(a, null, null, null);

                image.close();
                handler1.postDelayed(r1, 50);

            }
        };
        handler1.postDelayed(r1, 50);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_CODE:
                if (null != data) {
                    if (RESULT_OK == resultCode) {
                        mMediaProjection = mMediaProjectionManager.getMediaProjection(Activity.RESULT_OK, data);

                        r = new Runnable() {
                            @Override
                            public void run() {
                                startVirtual();
                            }
                        };
                        handler1.postDelayed(r, 5);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void createImageReader() {
        mImageReader = ImageReader.newInstance(mScreenWidth, mScreenHeight, PixelFormat.RGBA_8888, 2);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void startVirtual() {
        if (mMediaProjection != null) {
            virtualDisplay();
        }
    }

    private void stopVirtual() {
        if (mVirtualDisplay == null) {
            return;
        }
        mVirtualDisplay.release();
        mVirtualDisplay = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopVirtual();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void virtualDisplay() {
        mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror",
                mScreenWidth, mScreenHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(), null, null);
    }

    /**
     * Takes a screenshot of the current display and shows an animation.
     */
    Bitmap takeScreenshot(View view, int width, int height) {
        Class<?> cls = null;
        try {
            cls = Class.forName("android.view.SurfaceControl");
            Method method = cls.getDeclaredMethod("screenshot", int.class, int.class);
            Bitmap bitmap = (Bitmap) method.invoke(cls, width, height);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
